using System;
using System.Collections;
using System.Data;

using LocalBoard.Domain;

namespace LocalBoard.Persistence.MockAccessor
{
	/// <summary>
	/// Summary description for MockAttachmentAccessor.
	/// </summary>
	public class MockAttachmentAccessor : IAttachmentAccessor, IMockAccessor
	{
		private int _oId = 0;
		private DataTable _attachmentTable = new DataTable("Attachment");
		public static readonly MockAttachmentAccessor Instance = 
			new MockAttachmentAccessor();

		private MockAttachmentAccessor()
		{
			_attachmentTable.Columns.Add("Id", typeof(int));
			_attachmentTable.Columns.Add("Name", typeof(string));
			_attachmentTable.Columns.Add("Size", typeof(int));
			_attachmentTable.Columns.Add("Path", typeof(string));
			_attachmentTable.Columns.Add("Message_Id", typeof(int));
		}

		#region IMockAccessor Members
		public void ResetDataTable()
		{
			_oId = 0;
			_attachmentTable.Clear();
		}

		public void RemoveRows(int tableIndex, DataRow[] rows)
		{
			throw new NotImplementedException();
		}

		public DataRow[] ExecuteFilter(string filterExpression)
		{
			throw new NotImplementedException();
		}
		#endregion

		#region IAttachmentAccessor Members

		public ArrayList GetAttachmentListByMessageId(int messageId)
		{
			ArrayList attachmentList = new ArrayList();

			foreach(DataRow row in _attachmentTable.Select(string.Format("Message_Id={0}", messageId)))
			{
				attachmentList.Add(GetAttachmentFromResultRow(row));
			}
			return attachmentList;
		}

		public int Insert(Attachment attachment, int messageId)
		{
			_oId++;
			DataRow newRow = _attachmentTable.NewRow();
			
			newRow["Id"] = _oId;
			newRow["Name"] = attachment.Name;
			newRow["Size"] = attachment.Size;
			newRow["Path"] = attachment.Path;
			newRow["Message_Id"] = messageId;

			_attachmentTable.Rows.Add(newRow);

			return _oId;
		}

		public void Delete(int id)
		{
			DataRow row = FindAttachmentDataRow(id);
			if(row!=null)
			{
				_attachmentTable.Rows.Remove(row);
				_attachmentTable.AcceptChanges();
			}
		}

		#endregion

		private DataRow FindAttachmentDataRow(int id)
		{
			foreach(DataRow row in _attachmentTable.Rows)
			{
				if(DataConverter.GetInteger(row["Id"])==id)
					return row;
			}
			return null;
		}

		private Attachment GetAttachmentFromResultRow(DataRow row)
		{
			return new Attachment(DataConverter.GetInteger(row["Id"]), DataConverter.GetString(row["Name"]), DataConverter.GetInteger(row["Size"]),DataConverter.GetString(row["Path"]));
		}
	}
}
